
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import make_item


class JiangxiGzsayxrmzf215FPolicy(BaseTaxPolicySpider):
    name = "jiangxi_gzsayxrmzf_215f_policy"
    province: str = "江西省"  # 取表格
    city: str = "赣州市"  # 取表格
    county: str = "安远县"  # 取表格
    park: str = ""  # 取表格
    source: str = "赣州市安远县人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.ay.gov.cn/ayxxxgk/xxgkzfwj/xxgk_list.shtml"  # 注明入口网址，以便后续排错
    auto_next: bool = True

    def start_requests(self):
        yield from self.gen_request_by_index_create_page_html(
            url=self.url,
            next_page_href_xpath="//a[contains(text(), '下一页')]",
            list_a_xpath=["//*[@class='pageList newsList']//a[@title]"],
            total_page_xpath_reg=r"createPageHTML\('page_div',[\"\']?(\d+)[\"\']?,",
            end_tail="list",
            callback=self.parse_content
        )

    def parse_content(self, response, **kwargs):
        request = response.request
        content = response.text
        content = self.process_content(content)
        pre_data = self.parse_title_and_publish_time_by_gen(content)
        title = pre_data.get("title")
        publish_date = (
            response.xpath('//*[@name="PubDate"]/@content').get()
            or response.xpath('//*[@name="pub_date"]/@content').get()
            or pre_data.get("publish_time")
        )
        content = response.text
        content = self.process_content(content)

        item = dict(
            title=title,
            publish_date=publish_date,
            content=content,
            source_url=request.url,
            source=self.source,
            province=self.province,
            city=self.city,
            county=self.county,
            park=self.park,
        )
        if item['publish_date']:
            yield make_item(NetTaxPolicyItem, item)


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jiangxi_gzsayxrmzf_215f_policy".split())
